/**
 * 初始化区域管理详情对话框
 */
var AreaInfoDlg = {
    areaInfoData : {},
    validateFields: {
        name: {
            validators: {
                notEmpty: {
                    message: '区域名称不能为空'
                },
                stringLength: {  
                    max: 20,
                    message: '区域名称最大长度不能超过20'
                }
            }
        },
        warningValue: {
            validators: {
                notEmpty: {
                    message: '警戒值（人）不能为空'
                },
                regexp: {
                      regexp: /^[1-9]\d{0,17}$/,
                     message: '警戒值（人）只能输入0-18位整数'
                }
            }
        },
        saturationValue: {
            validators: {
                notEmpty: {
                    message: '饱和值（人）不能为空'
                },
                regexp: {
                      regexp: /^[1-9]\d{0,17}$/,
                     message: '饱和值（人）只能输入0-18位整数'
                }
            }
        },
        severeValue: {
            validators: {
                notEmpty: {
                    message: '严重值（人）不能为空'
                },
                regexp: {
                      regexp: /^[1-9]\d{0,17}$/,
                     message: '严重值（人）只能输入0-18位整数'
                }
            }
        }
    }
};

/**
 * 全局变量
 */
var oldPoint;//点对象
var map;//地图对象
var newPoint;//点对象
var overlays = [];

//地图样式
var styleJson = [
    {
        "featureType": "land",
        "elementType": "geometry",
        "stylers": {
            "color": "#e7f7fc"
        }
    },
    {
        "featureType": "water",
        "elementType": "all",
        "stylers": {
            "color": "#96b5d6"
        }
    },
    {
        "featureType": "green",
        "elementType": "all",
        "stylers": {
            "color": "#b0d3dd"
        }
    },
    {
        "featureType": "highway",
        "elementType": "geometry.fill",
        "stylers": {
            "color": "#a6cfcf"
        }
    },
    {
        "featureType": "highway",
        "elementType": "geometry.stroke",
        "stylers": {
            "color": "#7dabb3"
        }
    },
    {
        "featureType": "arterial",
        "elementType": "geometry.fill",
        "stylers": {
            "color": "#e7f7fc"
        }
    },
    {
        "featureType": "arterial",
        "elementType": "geometry.stroke",
        "stylers": {
            "color": "#b0d5d4"
        }
    },
    {
        "featureType": "local",
        "elementType": "labels.text.fill",
        "stylers": {
            "color": "#7a959a"
        }
    },
    {
        "featureType": "local",
        "elementType": "labels.text.stroke",
        "stylers": {
            "color": "#d6e4e5"
        }
    },
    {
        "featureType": "arterial",
        "elementType": "labels.text.fill",
        "stylers": {
            "color": "#374a46"
        }
    },
    {
        "featureType": "highway",
        "elementType": "labels.text.fill",
        "stylers": {
            "color": "#374a46"
        }
    },
    {
        "featureType": "highway",
        "elementType": "labels.text.stroke",
        "stylers": {
            "color": "#e9eeed"
        }
    }
]
/**
 * 清除数据
 */
AreaInfoDlg.clearData = function() {
    this.areaInfoData = {};
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
AreaInfoDlg.set = function(key, val) {
    this.areaInfoData[key] = (typeof val == "undefined") ? $("#" + key).val() : val;
    return this;
}

/**
 * 设置对话框中的数据
 *
 * @param key 数据的名称
 * @param val 数据的具体值
 */
AreaInfoDlg.get = function(key) {
    return $("#" + key).val();
}

/**
 * 关闭此对话框
 */
AreaInfoDlg.close = function() {
    parent.layer.close(window.parent.Area.layerIndex);
}

/**
 * 收集数据
 */
AreaInfoDlg.collectData = function() {
    $("#lon").val(newPoint.lng);
    $("#lat").val(newPoint.lat);
    this.set('id').set('city').set('district').set('name').set('type').set('description').set('isImportant').set('lon').set('lat').set('warningValue').set('saturationValue').set('severeValue');
}

/**
 * 验证数据是否为空
 */
AreaInfoDlg.validate = function () {
    $('#areaInfoForm').data("bootstrapValidator").resetForm();
    $('#areaInfoForm').bootstrapValidator('validate');
    return $("#areaInfoForm").data('bootstrapValidator').isValid();
}

/**
 * 提交添加
 */
AreaInfoDlg.addSubmit = function() {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }
    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/area/add", function(data){
        Feng.success("添加成功!");
        window.parent.Area.table.refresh();
        AreaInfoDlg.close();
    },function(data){
        Feng.error("添加失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.areaInfoData);
    ajax.start();
}

/**
 * 提交修改
 */
AreaInfoDlg.editSubmit = function() {

    this.clearData();
    this.collectData();

    if (!this.validate()) {
        return;
    }

    //提交信息
    var ajax = new $ax(Feng.ctxPath + "/area/update", function(data){
        Feng.success("修改成功!");
        window.parent.Area.table.refresh();
        AreaInfoDlg.close();
    },function(data){
        Feng.error("修改失败!" + data.responseJSON.message + "!");
    });
    ajax.set(this.areaInfoData);
    ajax.start();
}

//打点函数
function addMarker(point,isDrag,style){
    var marker;
    if(style != null){
        marker = new BMap.Marker(point,style);
    } else {
        marker = new BMap.Marker(point);
    }
    clearAll();
    if(isDrag == true){
        marker.enableDragging();
        marker.addEventListener("dragend",function(){
            newPoint = new BMap.Point(marker.getPosition().lng,marker.getPosition().lat);
        });
        overlays.push(marker);
    }
    map.addOverlay(marker);
}
//清除地图
function clearAll() {
    for(var i = 0; i < overlays.length; i++){
        map.removeOverlay(overlays[i]);
    } 
    overlays=[];
}

//初始化区县
function initDistrict(json){
    var html = ""; 
    var city =  $("#city").val();
    for (var key in json[city]) {
        html+="<option value='"+json[city][key]+"'>"+json[city][key]+"</option>";
    }
    $("#district").html(html);
}

$(function() {
    var cityDistrictJson = $("#cityDistrictJson").val();
    if(cityDistrictJson != null && cityDistrictJson != ""){
        cityDistrictJson = cityDistrictJson.replace(/'/g, '"');
        cityDistrictJson = $.parseJSON(cityDistrictJson);
        var html = ""; 
        for (var key in cityDistrictJson) {
            html+="<option value='"+key+"'>"+key+"</option>";
        }
        $("#city").html(html);
        initDistrict(cityDistrictJson);
    }
    
    var areaTypeJson = $("#areaTypeJson").val();
    if(areaTypeJson != null && areaTypeJson != ""){
        areaTypeJson = areaTypeJson.replace(/'/g, '"');
        areaTypeJson = $.parseJSON(areaTypeJson);
        var html = ""; 
        for (var key in areaTypeJson) {
            html+="<option value='"+areaTypeJson[key].type+"'>"+areaTypeJson[key].type+"</option>";
        }
        $("#type").html(html);
    }
    
    map = new BMap.Map("allmap",{enableMapClick: false});
    var cityHide = $("#cityHide").val();
    if(cityHide != null && cityHide != ""){
        $("#city").val(cityHide);
        initDistrict(cityDistrictJson);
    }
    var districtHide = $("#districtHide").val();
    if(districtHide != null && districtHide != ""){
        $("#district").val(districtHide);
    }
    var typeHide = $("#typeHide").val();
    if(typeHide != null && typeHide != ""){
        $("#type").val(typeHide);
    }
    var city = $("#city").val();
    var lon = $("#lon").val();
    var lat = $("#lat").val();
    if(lon == null || lon == ""){
        map.centerAndZoom(city, 11);
    }else{
        oldPoint = new BMap.Point(lon,lat);
        var myIcon = new BMap.Icon("http://api.map.baidu.com/img/markers.png", new BMap.Size(23, 25), {
            offset: new BMap.Size(10, 25),
            imageOffset: new BMap.Size(0, 0 - 12 * 25)
        });
        addMarker(oldPoint,false,{icon: myIcon});   
        map.centerAndZoom(oldPoint, 11);
    }
    map.setCurrentCity(city); 
    map.enableScrollWheelZoom(true);
    map.setMapStyle({styleJson:styleJson});
   

    //当map改变时重新打点
    map.addEventListener("tilesloaded",function(){
        if(newPoint != null && newPoint != ""){
            newPoint = new BMap.Point(newPoint.lng,newPoint.lat);
        }else{
            newPoint = new BMap.Point(map.getCenter().lng,map.getCenter().lat);
        }
        addMarker(newPoint,true,null);
    });

    //当地市改变时重新聚焦
    $("#city").change( function() {
        var select = $("#city").val();
        map.setCurrentCity(select);
        map.centerAndZoom(select, 11); 
        newPoint = null;
        initDistrict(cityDistrictJson);
    });

    Feng.initValidator("areaInfoForm", AreaInfoDlg.validateFields);
});
